package com.tong.calculator.exception;

import com.tong.calculator.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author: JiaqingTong Description: 全局异常处理
 * @Date: Created in 17:28$ 2021/8/11$
 * @Modified By : JiaqingTong
 */
@RestControllerAdvice(basePackages = "com.creator.controller")
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleError(MethodArgumentNotValidException e) {
        log.warn("Method Argument Not Valid", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        return R.build("400", message);
    }

    /**
     * 拦截参数校验异常
     *
     * @param e 异常信息
     * @return R对象
     */
    @ExceptionHandler(BindException.class)
    public R handleMethodArgumentNotValidException(BindException e) {
        log.error("请求参数异常", e);
        String message = "参数错误:";
        FieldError fieldError = e.getBindingResult().getFieldError();
        if (fieldError != null) {
            message += fieldError.getDefaultMessage();
        }
        return R.error(message);
    }

    /**
     * 拦截自定义异常
     *
     * @param e 异常信息
     * @return R对象
     */
    @ExceptionHandler(ServiceException.class)
    public R handleServiceException(ServiceException e) {
        log.error("未知异常", e);
        String message = e.getMessage();

        return R.error(message);
    }


    /**
     * 拦截其他异常
     *
     * @param e 异常信息
     * @return R对象
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error("未知异常", e);
        String message = "未知异常";

        return R.error(message);
    }


}
